<template>
  <div class='container'>
    <!-- 卡片 -->
    <el-card>
      <template #header>
        试题录入
      </template>
      <!-- 表单 -->
      <el-form label-width="100px" :model="questionRes" :rules="rules" ref="ruleForm">
        <el-form-item label="学科" prop="subjectID">
          <el-select v-model="questionRes.subjectID" placeholder="请选择">
           <el-option
             v-for="item in subjectOptionFirst"
             :key="item.value"
             :label="item.label"
             :value="item.value">
           </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
           <el-select  v-model="questionRes.catalogID" placeholder="请选择">
             <el-option
               v-for="item in subjectOptionSecond"
               :key="item.value"
               :label="item.label"
               :value="item.value">
             </el-option>
           </el-select>
         </el-form-item>
         <el-form-item label="企业:" prop="enterpriseID">
          <el-select v-model="questionRes.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companysOption"
              :key="item.id"
              :label="item.shortName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="城市:" prop="city">
          <el-select v-model="questionRes.province" placeholder="请选择" class="city">
            <el-option
              v-for="item in cityOption"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <el-select v-model="questionRes.city" placeholder="请选择" class="city">
            <el-option
              v-for="item in areaOption"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="方向:"  prop="direction">
          <el-select v-model="questionRes.direction" placeholder="请选择">
            <el-option
              v-for="item in directionOption"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="questionRes.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="questionRes.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quillEditor v-model="questionRes.question" :options="editorOption"></quillEditor>
        </el-form-item>
        <el-form-item label="选项:" v-if="questionRes.questionType==='1'||questionRes.questionType==='2'">
          <el-row :style="{width:'400px'}" v-for="(item,index) in questionRes.options" :key="index">
            <el-col :span="3">
              <el-radio v-if="questionRes.questionType==='1'" v-model="item.isRight" @input="changeRadio(index)" :label="true">{{item.code}}:</el-radio>
              <el-checkbox v-else-if="questionRes.questionType==='2'" v-model="item.isRight">{{item.code}}:</el-checkbox>
            </el-col>
            <el-col :span="15">
              <el-input v-model="item.title" :style="{width:'240px'}"></el-input>
            </el-col>
            <el-col :span="6">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="(res,file)=>{handleAvatarSuccess(index,res,file)}">
                <img v-if="item.img" :src="item.img" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
          </el-row>
          <el-button type="danger" @click="addAnswer">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频:">
          <el-input v-model="questionRes.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <quillEditor v-model="questionRes.answer" :options="editorOption"></quillEditor>
        </el-form-item>
        <el-form-item label="题目备注:">
           <el-input
             type="textarea"
             :rows="2"
             placeholder="请输入内容"
             v-model="questionRes.remarks">
           </el-input>
        </el-form-item>
        <el-form-item label="试题标签">
          <el-select  v-model="questionRes.tags" placeholder="请选择">
            <el-option
              v-for="item in tagsOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="quesSubmit">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/companys.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as tagssimple } from '@/api/hmmm/tags.js'
import { simple as directorysimple } from '@/api/hmmm/directorys.js'
export default {
  data () {
    return {
      subjectOptionFirst: [],
      subjectOptionSecond: [],
      companysOption: [],
      tagsOption: [],
      cityOption: [],
      areaOption: [],
      directionOption: [
        {
          value: 'o2o'
        }, {
          value: '外包服务'
        }, {
          value: '企业服务'
        }, {
          value: '互联网金融'
        }, {
          value: '企业咨询'
        }, {
          value: '互联网'
        }, {
          value: '电子商务'
        }, {
          value: '其他'
        }
      ],
      questionRes: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          {
            isRight: false,
            code: 'A',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用  代码块
            ['code-block', 'image', 'video'] // 链接、图片、视频
          ]
        }
      },
      rules: {
        subjectID: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入必填项', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    quillEditor
  },
  async created () {
    if (this.$route.query.id) {
      const { data: datares } = await detail({ id: this.$route.query.id })
      datares.options.forEach(item => { item.isRight = item.isRight !== 0 })
      datares.options.sort((a, b) => a.id - b.id)
      this.questionRes = JSON.parse(JSON.stringify(datares))
      this.$nextTick(() => {
        this.questionRes.city = datares.city
        this.questionRes.catalogID = datares.catalogID
      })
      this.questionRes.city = datares.city
    }
    const subjectRes = await simple()
    const { data } = await list({ pagesize: 10000 })
    this.companysOption = data.items
    this.subjectOptionFirst = subjectRes.data
    this.cityOption = provinces()
  },
  watch: {
    'questionRes.subjectID': {
      async handler (value) {
        this.questionRes.catalogID = ''
        this.questionRes.tags = ''
        const tafres = await tagssimple({ subjectID: value })
        const dirres = await directorysimple({ subjectID: value })
        this.subjectOptionSecond = dirres.data
        this.tagsOption = tafres.data
      }
    },
    'questionRes.province': {
      handler (value) {
        this.areaOption = citys(value)
        this.questionRes.city = ''
      }
    },
    'questionRes.questionType': {
      handler (value) {
        if (value === 1) {
          this.questionRes.options.forEach(item => { item.isRight = false })
        }
      }
    }
  },
  methods: {
    changeRadio (index) {
      this.questionRes.options.forEach(item => { item.isRight = false })
      this.questionRes.options[index].isRight = true
    },
    handleAvatarSuccess (index, res, file) {
      this.questionRes.options[index].img = URL.createObjectURL(file.raw)
    },
    addAnswer () {
      const word = this.questionRes.options[this.questionRes.options.length - 1].code
      const newword = String.fromCharCode(word.charCodeAt(0) + 1)
      this.questionRes.options.push({
        isRight: false,
        code: newword,
        title: '',
        img: ''
      })
    },
    async quesSubmit () {
      try {
        await this.$refs.ruleForm.validate()
        if (this.$route.query.id) {
          await update(this.getValue(this.questionRes))
          this.$message.success('修改成功')
        } else {
          await add(this.getValue(this.questionRes))
          this.$message.success('添加成功')
        }
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
      }
    },
    getValue (obj) {
      const newobj = {}
      for (const k in obj) {
        if (obj[k]) {
          newobj[k] = obj[k]
        }
      }
      newobj.difficulty = String(newobj.difficulty)
      newobj.questionType = String(newobj.questionType)
      return newobj
    }
  }

}
</script>

<style scoped lang='less'>
.el-select {
  width: 400px;
}
.quill-editor {
  height: 200px;
  margin-bottom: 50px;
}
.el-textarea{
  width: 400px;
}
.el-input{
  width: 400px;
}
.city{
  width: 200px;
}
</style>
